package com.lc.config;

import com.lc.pojo.User;
import com.lc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import com.lc.mapper.UserMapper;
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;


    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权");

        // 拿到当前登陆用户的这个对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        // 从数据库获取当前用户的权限,若满足则放行
        info.addStringPermission(currentUser.getId());

        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");


        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 用户名，密码：数据中取
        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null){
            // 登录失败
            return null;
        }

        // 密码认证shiro做,加密MD5
        return new SimpleAuthenticationInfo(user,user.getUser_pwd(),"");
    }
    }


